class Solution:

    def findTheLongestBalancedSubstring(self, s: str) -> int:
        n = len(s)
        a = [[0] * 2 for _ in range(n)]
        a[0][0] = 1 if s[0] == '0' else 0
        a[0][1] = 1 if s[0] == '1' else 0
        ans = 0
        for i in range(1, n):
            a[i][0], a[i][1] = a[i - 1][0], a[i - 1][1]
            a[i][int(s[i])] += 1
            if a[i][0] == a[i][1]:
                ans = i + 1
            else:
                j = 0
                while j < i and a[i][0] - a[j][0] != a[i][1] - a[j][1]:
                    j += 1
                ans = max(ans, i - j)
        return ans


class Solution:

    def findTheLongestBalancedSubstring(self, s: str) -> int:
        n, i, ans = len(s), 0, 0
        while i < n:
            while i < n and s[i] != '0':
                i += 1
            z = 0
            while i < n and s[i] == '0':
                i += 1
                z += 1
            o = 0
            while i < n and s[i] == '1':
                i += 1
                o += 1 
            ans = max(ans, min(z, o) * 2)
        return ans